import { defineComponent, h, ref, watch } from 'vue'
import {
  NTabs,
  NTabPane,
  NIcon,
  NButton,
  NDropdown,
  NPopselect
} from 'naive-ui'
import { MenuSharp, Refresh } from '@vicons/ionicons5'
import * as tabs from '@/views/tabs'
import styles from './index.module.scss'
import { useRoute, useRouter } from 'vue-router'
import TabsUtils from '@/store/tabs/tabs-util'

export default defineComponent({
  name: 'TabsBar',
  setup() {
    const store = window.$store
    const t = window.$t
    const tabsNavContextmenuProps = ref({
      left: 0,
      top: 0,
      tabName: ''
    })
    const tabsNavContextmenuShow = ref(false)
    const route = useRoute()
    // 监听路由的变化（防止浏览器后退/前进不变化 tabsMenuValue）
    watch(
      () => route,
      () => {
        if (route.path === '/') return
        TabsUtils.addPane(
          route.path,
          route.query.tab as string,
          route.query.tabName as string,
          route.query
        )
      },
      {
        immediate: true,
        deep: true
      }
    )
    const selectTab = ref('')
    return {
      store,
      t,
      tabsNavContextmenuProps,
      tabsNavContextmenuShow,
      selectTab
    }
  },
  watch: {
    tabsNavContextmenuShow(value) {
      if (value) {
        document.body.addEventListener('click', this.closeTabsNavContextmenu)
      } else {
        document.body.removeEventListener('click', this.closeTabsNavContextmenu)
      }
    }
  },
  mounted() {
    //标签页右键菜单绑定
    const tabsNav = document.querySelector(
      'div[class="n-tabs-nav-scroll-content"]'
    )
    tabsNav?.addEventListener('contextmenu', (e) => {
      if (
        e.target.className === 'n-tabs-tab n-tabs-tab--closable' ||
        e.target.className ===
          'n-tabs-tab n-tabs-tab--active n-tabs-tab--closable'
      ) {
        e.preventDefault()
        this.openTabsNavContextmenu(e as PointerEvent)
        this.tabsNavContextmenuProps.tabName = e.target.dataset.name
      } else if (e.target.className === 'n-tabs-tab__label') {
        e.preventDefault()
        this.openTabsNavContextmenu(e as PointerEvent)
        this.tabsNavContextmenuProps.tabName = e.target.parentNode.dataset.name
      }
    })
  },
  methods: {
    openTabsNavContextmenu(e: PointerEvent) {
      const x = e.pageX
      const y = e.pageY
      this.tabsNavContextmenuProps.top = y
      this.tabsNavContextmenuProps.left = x
      this.tabsNavContextmenuShow = true //在这里控制右键菜单的打开
    },
    closeTabsNavContextmenu() {
      this.tabsNavContextmenuShow = false
    },
    handleClose(name: string) {
      if (this.store.state.tabPanes.length === 1) {
        window.$message.info(this.t('common.lastOneTabCloseTips'))
        return
      }
      this.store.commit('closePane', name)
    },
    handleClosePane() {
      if (this.store.state.tabPanes.length === 1) {
        window.$message.info(this.t('common.lastOneTabCloseTips'))
        return
      }
      this.store.commit('closePane', this.tabsNavContextmenuProps.tabName)
    },
    handleCloseOther() {
      this.store.commit('closeOtherPane', this.tabsNavContextmenuProps.tabName)
    },
    handleUp(name: string) {
      this.store.commit('updateTabPaneSelected', name)
    },
    refresh() {
      this.store.commit('refreshCurrentPane')
    }
  },

  render() {
    return h('div', null, [
      h(
        NTabs,
        {
          value: this.store.state.tabPaneSelected,
          type: 'card',
          style: { position: 'relation', backgroundColor: '#f8f8fc' },
          closable: true,
          tabStyle: 'min-width: 80px;--n-tab-color: #efefef',
          paneStyle:
            'margin:0 3px;--n-pane-padding:10px 0px 0 0px;background-color:#f8f8fc;position:absolute;top:42px;left:0;bottom:0;width:calc(100% - 6px);overflow:auto',
          onClose: this.handleClose,
          onUpdateValue: this.handleUp
        },
        {
          default: [
            ...this.store.state.tabPanes.map((item: any) => {
              return h(
                NTabPane,
                {
                  tab: item.tab,
                  name: item.name,
                  displayDirective: 'show'
                },
                h(tabs[item.tabName], item.attrs)
              )
            })
          ],
          suffix: h(
            'div',
            { style: 'margin-right: 16px' },
            h(
              NPopselect,
              {
                value: this.store.state.tabPaneSelected,
                size: 'medium',
                scrollable: true,
                options: this.store.state.tabPanes.map((item) => {
                  return {
                    value: item.name,
                    label: item.tab
                  }
                }),
                onUpdateValue: this.handleUp
              },
              h(
                NIcon,
                {
                  size: '24px'
                },
                { default: () => h(MenuSharp) }
              )
            )
          )
        }
      ),
      h(
        'ul',
        {
          style: {
            display: this.tabsNavContextmenuShow ? 'block' : 'none',
            left: this.tabsNavContextmenuProps.left + 'px',
            top: this.tabsNavContextmenuProps.top + 'px'
          },
          class: styles.contextmenu
        },
        [
          h(
            'li',
            {
              onClick: this.refresh
            },
            window.$t('common.refreshCurrentTab')
          ),
          h(
            'li',
            {
              onClick: this.handleClosePane
            },
            window.$t('common.closeTab')
          ),
          h(
            'li',
            {
              onClick: this.handleCloseOther
            },
            window.$t('common.closeOtherTab')
          )
        ]
      )
    ])
  }
})
